<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    modal-class="lowcode-dialog"
    destroy-on-close
    v-bind="attr"
    @close="close"
  >
    <div class="body-box">
      <Body :body="schema.body" />
    </div>
    <el-row type="flex" justify="end" align="middle" class="footer">
      <LowCode v-for="(item, index) in actions" :key="item.key || index" :schema="item" />
    </el-row>
  </el-dialog>
</template>

<script setup>
import { defineProps, reactive, ref, provide, watchEffect } from 'vue'
import Body from '../body/index.vue'
import { filterAttr } from '../../common/util'
import LowCode from '@/components/LowCode.vue'

defineOptions({ name: 'DialogCom' })

defineExpose({
  show,
  hide
})

const form = reactive({})

provide('lowCodeDialog', {
  hide,
  setForm(_form) {
    for (const [key, value] of Object.entries(_form)) {
      form[key] = value
    }
  }
})
provide('lowCodeForm', form)

const visible = ref(false)

const props = defineProps({
  schema: {
    type: Object,
    required: true
  }
})
const attr = ref()
const actions = ref(props.schema.actions || [])

watchEffect(() => {
  attr.value = filterAttr(props.schema)

  const schema = props.schema
  actions.value = []
  if (!schema.actions) {
    if (schema.cancelButton) {
      actions.value.push(schema.cancelButton)
    } else {
      actions.value.push({
        type: 'button',
        actionType: 'cancel',
        body: '取消'
      })
    }
    if (schema.confirmButton) {
      actions.value.push(schema.confirmButton)
    } else {
      actions.value.push({
        type: 'button',
        actionType: 'submit',
        level: 'primary',
        body: '确认'
      })
    }
  }
})

function show() {
  visible.value = true
}

function hide() {
  visible.value = false
}

function close() {
  if (form.resetFields) {
    form.resetFields()
  }
}
</script>

<style lang="scss" scoped>
.body-box {
  padding: 10px;
}
.footer {
  padding: 10px;
  border-top: 1px solid var(--el-bg-color-page);
}
</style>
<style lang="scss">
.lowcode-dialog {
  .el-dialog__header {
    padding: 10px;
    border-bottom: 1px solid var(--el-bg-color-page);
  }
  .el-dialog__body {
    padding: 0;
  }
}
</style>
